package com.hxzy.filters;


import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.hxzy.pojo.Result;
import com.hxzy.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * @author wzm
 * @create 2024-03-08 15:46
 * project_name:JavaWeb2401
 * @Description
 */
//利用过滤器来实现登录的令牌检验
//@WebFilter(urlPatterns = "/*")//拦截所有请求
@Slf4j
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
       // 前置条件 父类接口无法使用子类中相关获取的方法 强转
        HttpServletRequest request  = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        //1.获取请求服务器的url地址
        String url = request.getRequestURL().toString();
        log.info("请求url{}",url);

        //2.判断url是否包含login 如果包含说明是的登录操作  直接放行
        if(url.contains("/login")){
                   filterChain.doFilter(request,response);     //放行
            return;
        }

        //3.不是login的请求  判断令牌

        //获取令牌
        String token = request.getHeader("token");
        log.info("请求token{}",token);


        //令牌为空 直接返回没有登录给前端
        if(!StringUtils.hasLength(token)){
            log.info("token不存在{}",token);
            //获得要响应的错误对象  将错误对象java=>json字符串
            Result result = Result.error("NOT_LOGIN");
            String s = JSON.toJSONString(result);

            //返回错误结果
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(s);
            return;
        }

        //令牌不为空  解析令牌是否被篡改或是否正确
        try {
            JwtUtils.parseJwt(token);
        }catch (Exception e){
            //解析失败返回错误结果 未登录
            log.info("jwt解析出现错误");
            //获得要响应的错误对象  将错误对象java=>json字符串
            Result result = Result.error("NOT_LOGIN");
            String s = JSON.toJSONString(result);

            //返回错误结果
            response.setContentType("application/json;charset=utf-8");
          response.getWriter().write(s);
            return;
        }

        //解析成功 放行该做什么做什么
        filterChain.doFilter(request,response);//所以if都没进

    }
}
